package com.xm.servlet.reception_desk.order_settlement;

import com.google.gson.Gson;
import com.xm.entity.*;
import com.xm.exception.SqlErrorException;
import com.xm.service.reception_desk.*;
import com.xm.util.DecryptExampleUtil;
import com.xm.util.DiscountConverterUtil;
import lombok.SneakyThrows;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 订单页面
 *
 * @author 康文程
 * @date 2023-12-22 下午 02:56
 */
@WebServlet("/order/settlement")
public class OrderSettlementServlet extends HttpServlet {
    /**
     * 地址Service
     */
    private final AddressService service = new AddressService();
    /**
     * 是否免运费 0免运费 1不免运费
     */
    private Integer isFreeShipping = 1;

    @SneakyThrows(Exception.class)
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        //AES解密
        String informationId = DecryptExampleUtil.decrypt(req.getParameter("informationId"));
        req.setAttribute("addressList",service.getAllAddresses(Integer.parseInt(informationId)));
        confirmOrder(Integer.parseInt(informationId),req);
        req.setAttribute("informationId",Integer.parseInt(informationId));
        req.getRequestDispatcher("/WEB-INF/page/reception_desk/order_settlement.jsp").forward(req, resp);
    }

    /**
     * 被选中商品的大类别Id
     */
    private String categoryIds = null;
    /**
     * 是否第一次
     */
    private int isFirst = 0;
    /**
     * 确认下单
     * @param informationId 用户信息Id
     * @throws SqlErrorException 抛出错误
     */
    public void confirmOrder(Integer informationId, HttpServletRequest req) throws SQLException {
        //购物车Service
        final ShoppingCartService shoppingCartService = new ShoppingCartService();
        //商品规格Service
        final CommoditySpecificationService commoditySpecificationService = new CommoditySpecificationService();
        //商品保险Service
        final CommodityInsuranceService commodityInsuranceService = new CommodityInsuranceService();
        //商品服务Service
        final CommodityServeService commodityServeService = new CommodityServeService();
        //商品优惠卷Service
        final CouponsService couponsService = new CouponsService();
        //用户信息Service
        final AccountInformationService accountInformationService = new AccountInformationService();

        //查询被选中的购物车商品并且查询出限购数量的库存数量
        List<ShoppingCart> shoppingCartByInformationId =
                shoppingCartService.getSelectedShoppingCartByInformationId(informationId);
        //循环打印规格id
        shoppingCartByInformationId.forEach(e -> {
            String separate = ",";
            StringBuilder commodityName =
                    new StringBuilder(e.getCommodity().getCommodityName());
            //是否有多个Ids
            if (e.getSpecificationIds().contains(separate)){
                //多个id使用,分隔
                for (String specificationId : e.getSpecificationIds().split(separate)) {
                    //循环查询规格名称
                    String specificationNameById =
                            commoditySpecificationService.getSpecificationNameById(
                                    Integer.parseInt(specificationId));
                    //规格和商品名称拼接起来
                    commodityName.append("   ").append(specificationNameById);
                }
            }else{
                //如果只有一个Id则直接查询规格名称
                String specificationNameById =
                        commoditySpecificationService.getSpecificationNameById(
                                Integer.parseInt(e.getSpecificationIds()));
                //规格和商品名称拼接起来
                commodityName.append("   ").append(specificationNameById);
            }
            String notNull = "";
            //判断用户是否购买了商品保险和是否存在多个商品保险
            if (e.getInsuranceIds() != null && e.getInsuranceIds().contains(separate)){
                ArrayList<CommodityInsurance> multipleCommodityInsuranceId = new ArrayList<>();
                //查询商品保险 存在多个Id
                for (String insuranceId : e.getInsuranceIds().split(separate)) {
                    CommodityInsurance insuranceById = commodityInsuranceService.getInsuranceById(
                            Integer.parseInt(insuranceId)
                    );
                    multipleCommodityInsuranceId.add(insuranceById);
                }
                e.setCommodityInsuranceList(multipleCommodityInsuranceId);
            }else if (!notNull.equals(e.getInsuranceIds()) && e.getInsuranceIds() != null){
                //只有一个Id
                CommodityInsurance insuranceById = commodityInsuranceService.getInsuranceById(
                        Integer.parseInt(e.getInsuranceIds())
                );
                ArrayList<CommodityInsurance> singleCommodityInsuranceId = new ArrayList<>();
                singleCommodityInsuranceId.add(insuranceById);
                e.setCommodityInsuranceList(singleCommodityInsuranceId);
            }
            if (e.getInsuranceIds() != null){
                List<CommodityInsurance> insurancesByIds =
                        commodityInsuranceService.getInsurancesByIds(e.getInsuranceIds(),e.getCommodity().getCommodityId());
                e.setMerchandiseInsuranceNotAddedList(insurancesByIds);
            }
            //判断是否是小米发货 是小米发货则免运费
            try {
                boolean selfEmployedByCommodityId = commodityServeService.isSelfEmployedByCommodityId(e.getCommodityId());
                if (selfEmployedByCommodityId && isFreeShipping != 0){
                    isFreeShipping = 0;
                }
            } catch (SqlErrorException ex) {
                throw new RuntimeException(ex);
            }
            if (e.getCommodity().getCategory().getCategoryId() != null && isFirst == 0){
                categoryIds = e.getCommodity().getCategory().getCategoryId().toString();
                isFirst = 1;
            }else if (e.getCommodity().getCategory().getCategoryId() != null){
                categoryIds += ","+e.getCommodity().getCategory().getCategoryId();
            }
            //重新放入
            e.setCommodity(new Commodity(e.getCommodity().getCommodityId(),
                    commodityName.toString(),
                    e.getCommodity().getCommodityImages(),
                    e.getCommodity().getCommodityState(),
                    e.getCommodity().getCommodityDiscount() == 0 ? e.getCommodity().getCommodityPrice() :
                            DiscountConverterUtil.calculateDiscount(e.getCommodity().getCommodityPrice(), e.getCommodity().getCommodityDiscount())));
        });
        List<Coupons> couponsByCategoryId = new ArrayList<>();
        if (categoryIds != null){
            couponsByCategoryId = couponsService.getAvailableCouponsByCategoryIdsAndInformationId(categoryIds,informationId);
        }
        //传给前端 用户信息表
        req.setAttribute("informationId", informationId);
        //用户名称
        req.setAttribute("name",accountInformationService.getNameByInformationId(informationId));
        Address addressesByInformationIdAndSelected = service.getAddressesByInformationIdAndSelected(informationId) == null
                ? new Address() : service.getAddressesByInformationIdAndSelected(informationId);
        //被选中的地址
        req.setAttribute("selectAddress",addressesByInformationIdAndSelected);
        //优惠卷
        req.setAttribute("couponList",couponsByCategoryId);
        //是否免运费
        req.setAttribute("isFreeShipping",isFreeShipping);
        //账号Id
        req.setAttribute("accountId",req.getParameter("account"));
        //购物车
        req.setAttribute("shoppingCartList", shoppingCartByInformationId);
    }

    /**
     * 修改或添加
     * @param req  an {@link HttpServletRequest} object that
     *             contains the request the client has made
     *             of the servlet
     * @param resp an {@link HttpServletResponse} object that
     *             contains the response the servlet sends
     *             to the client
     */
    @SneakyThrows(Exception.class)
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        String addressJson = req.getParameter("addressJson");
        Address address = new Gson().fromJson(addressJson, Address.class);
        resp.getWriter().println(service.saveOrUpdateAddress(address));
    }
}
